package com.fagp.mew.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fagp.mew.cms.messages.PageRequest;
import com.fagp.mew.cms.messages.PageResponse;
import com.mew.common.config.RedisConstantValue;
import com.mew.common.dc.db.ProfileService;
import com.mew.common.dc.db.UserService;
import com.mew.common.dc.mapper.UserMapper;
import com.mew.common.dc.redis.GameRoomRedisService;
import com.mew.common.dc.redis.UserProfileRedisService;
import com.mew.common.entity.config.Game;
import com.mew.common.entity.config.Room;
import com.mew.common.entity.user.Profile;
import com.mew.common.entity.user.User;
import com.mew.common.rest.bo.MewSession;
import com.mew.common.util.StringUtils;
import com.mew.common.vo.web.OnlineVo;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author K.Song
 * @Date 2020/11/6 0006
 **/
@Service
@Slf4j
public class WebRedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private GameRoomRedisService gameRoomRedisService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProfileService profileService;
    @Autowired
    private UserMapper userMapper;

    public PageResponse getOnlineUserProfile(PageRequest pageRequest, Integer roomId){

        ArrayList<OnlineVo> resList = new ArrayList<>();

        List<Game> allGame = gameRoomRedisService.findAllGame();
        Map<Integer, Game> gameMap = allGame.stream().collect(Collectors.toMap(Game::getId, g -> g));
        gameMap.put(-9,Game.builder().name("").build());
        gameMap.put(0,Game.builder().name("大厅").build());
        Map<Integer, Room> allRooms = getAllRoom();
        allRooms.put(-9,new Room());
        allRooms.put(0,new Room());

        int leng = 0;

        if (StringUtils.isEmpty(pageRequest.getKey())||StringUtils.isEmpty(pageRequest.getValue())){
            //普通
            List<MewSession> list = redisTemplate.opsForHash().values(RedisConstantValue.SESSION_USER).stream().map(m -> (MewSession) m).filter(i -> i.onl == 1).collect(Collectors.toList());
            leng = list.size();
            int page = pageRequest.getPage();
            int size = pageRequest.getLimit();
            //分页
            int min = (page-1)*size;
            int maxSize = page*size>list.size()?list.size():page*size;

            for (int i = min ; i < maxSize ; i++) {
                MewSession mewSession = list.get(i);
                OnlineVo vo = doVo(gameMap, allRooms, mewSession);

                resList.add(vo);
            }

        }else {
            List<User> users = userMapper.selectList(new QueryWrapper<User>().likeLeft(pageRequest.getKey(), pageRequest.getValue()));

            for (User user : users) {
                MewSession mewSession = (MewSession) redisTemplate.opsForHash().get(RedisConstantValue.SESSION_USER, user.getId());
                if (null==mewSession){
                    mewSession = new MewSession();
                    mewSession.uid = user.getId();
                }

                OnlineVo vo = doVo(gameMap, allRooms, mewSession);
                resList.add(vo);
            }

        }


        return PageResponse.builder().count(leng).data(resList).build();


    }

    @NotNull
    private OnlineVo doVo(Map<Integer, Game> gameMap, Map<Integer, Room> allRooms, MewSession mewSession) {
        User user = userService.getRedisUserById(mewSession.uid);
        Profile profile = profileService.getRedisProfileById(mewSession.uid);
        OnlineVo vo = OnlineVo
                .builder()
                .id(user.getId())
                .win(mewSession.pmt - mewSession.bt)
                .GameName(gameMap.get(mewSession.gid).getName())
                .roomName(allRooms.get(mewSession.rid).getName())
                .build();

        onlineVo(vo,user,profile);
        return vo;
    }

    public Map<Integer, Room> getAllRoom() {
        List<Game> allGame = gameRoomRedisService.findAllGame();
        ArrayList<Room> rooms = new ArrayList<>();
        for (Game game : allGame) {
            List<Room> room = gameRoomRedisService.findRoomByGameId(game.getId());
            rooms.addAll(room);
        }
        Map<Integer, Room> map = rooms.stream().collect(Collectors.toMap(Room::getId, r -> r));
        return map;
    }

    public Map<Integer, Game> getAllGame(){
        List<Game> allGame = gameRoomRedisService.findAllGame();
        Map<Integer, Game> gameMap = allGame.stream().collect(Collectors.toMap(Game::getId, g -> g));
        return gameMap;
    }

    private void onlineVo(OnlineVo vo, User user,Profile profile) {

        vo.setGid(user.getGid());
        vo.setNickname(user.getNickname());

        if (null!=profile){
            vo.setGold(profile.getGoldNumber());
            vo.setAward(String.format("%.2f", Optional.ofNullable(profile.getPaymentTotal()).orElse(0l)*100/Optional.ofNullable(profile.getBetTotal()).orElse(0l).doubleValue()));
            vo.setBetGoldNumber(profile.getBetTotal());
            vo.setPaymentTotal(profile.getPaymentTotal());
            vo.setWinlose(Optional.ofNullable(profile.getPaymentTotal()).orElse(0l)-Optional.ofNullable(profile.getBetTotal()).orElse(0l));
        }
    }



}
